package com.jijs.framework.core.taglib;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.jijs.framework.model.pmodel.AdeUser;
import com.jijs.framework.util.StringUtil;
import com.jijs.framework.util.UserUtil;

/**
 * 根据权限控制的按钮
 * 
 * @author jijs
 */
public class RoleLinkButtonTag extends TagSupport {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 2871167818814453701L;

	/** 权限串 */
	private String permission = null;

	/** onclick事件 */
	private String onclick = null;

	/** 连接的访问地址 */
	private String href = null;

	/** css的class */
	private String styleClass = null;

	/** data-option */
	private String dataOptions = null;

	public void setPermission(String permission) {
		this.permission = permission;
	}

	public void setOnclick(String onclick) {
		this.onclick = onclick;
	}

	public void setHref(String href) {
		this.href = href;
	}

	public void setStyleClass(String styleClass) {
		this.styleClass = styleClass;
	}

	public void setDataOptions(String dataOptions) {
		this.dataOptions = dataOptions;
	}

	@Override
	public int doStartTag() throws JspException {

		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		AdeUser user = UserUtil.getLoginUser(request);

		// 如果没有权限，则什么都不显示
		if (!user.getModuleList().contains(permission)) {
			return TagSupport.SKIP_BODY;
		}

		// 开始拼接页面
		StringBuffer sb = new StringBuffer();
		sb.append("<a");

		if (!StringUtil.isEmpty(onclick)) {
			sb.append(" onclick=\"");
			sb.append(onclick);
			sb.append("\"");
		}

		if (StringUtil.isEmpty(href)) {
			sb.append(" href=\"javascript:void(0);\"");
		} else {
			sb.append(" href=\"");
			sb.append(href);
			sb.append("\"");
		}

		if (StringUtil.isEmpty(styleClass)) {
			sb.append(" class=\"easyui-linkbutton\"");
		} else {
			sb.append(" class=\"");
			sb.append(styleClass);
			sb.append("\"");
		}

		sb.append(" data-options=\"");
		sb.append(dataOptions);
		sb.append("\">");

		JspWriter writer = null;

		try {
			writer = pageContext.getOut();
			writer.write(sb.toString());
			writer.flush();
		} catch (IOException e) {
			throw new JspException(e);
		}

		return TagSupport.EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {

		JspWriter writer = null;

		try {
			writer = pageContext.getOut();
			writer.write("</a>");
			writer.flush();
		} catch (IOException e) {
			throw new JspException(e);
		}

		return TagSupport.EVAL_PAGE;
	}
}
